package com.net.wanjian.networkhospitalmanager.activity.skilltrain;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.ScanPortraitActivity;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.adapter.LaboratoryListAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.base.RecyclerBaseAdapter;
import com.net.wanjian.networkhospitalmanager.bean.DeviceOperationListResult;
import com.net.wanjian.networkhospitalmanager.bean.ScanDeviceQRCodeResult;
import com.net.wanjian.networkhospitalmanager.bean.SearchDeviceDetailResult;
import com.net.wanjian.networkhospitalmanager.bean.StudentApplyReserveReturn;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.ProgressDialogUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.net.wanjian.networkhospitalmanager.view.NoDataEmptyView;
import com.net.wanjian.networkhospitalmanager.widge.RefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;

/**
 * 此activity专为学生历史预约实验服务，和实验列表页面公用一个布局
 */
public class StudentHistoryLaboratoryListActivity extends BaseActivity {
    public static final String LAB_RESERVE_MEMBER_ID_KEY = "com.net.wanjian.activity.laboratorylistactivity.lab_reserve_member_id_key";
    public static final String LAB_RESERVE_NAME_KEY = "com.net.wanjian.activity.laboratorylistactivity.lab_reserve_name_key";
    public static final String LAB_RESERVE_ID_KEY = "com.net.wanjian.activity.laboratorylistactivity.lab_reserve_id_key";
    public static final String LAB_RESERVE_BROAST_INTENT_REFRESH = "com.net.wanjian.activity.laboratorylistactivity.refreshlist";


    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.top_title_tv)
    TextView topTitleTv;
    @BindView(R.id.laboratory_list_recycler_view)
    RefreshRecyclerView laboratoryListRecyclerView;
    @BindView(R.id.laboratory_scan_qrcode_layout)
    RelativeLayout laboratoryScanQrcodeLayout;
    @BindView(R.id.laboratory_list_nodata_view)
    NoDataEmptyView noDataEmptyView;
    @BindView(R.id.laboratory_progress)
    ProgressBar mProgressBar;

    private LaboratoryListAdapter mListAdapter;
    private String labReserveMemberID;
    private String labReserveID;
    private List<DeviceOperationListResult.DataBean.LabReserveMemberOperationListBean> operationList;


    @Override
    protected void initData() {
        operationList = new ArrayList<>();
        laboratoryScanQrcodeLayout.setVisibility(View.GONE);


        IntentFilter filter = new IntentFilter();
        filter.addAction(LAB_RESERVE_BROAST_INTENT_REFRESH);

        Bundle bundle = getIntent().getExtras();
        String labName = "";
        if (null != bundle){
            labReserveMemberID = bundle.getString(StudentHistoryLaboratoryListActivity.LAB_RESERVE_MEMBER_ID_KEY);
            labReserveID = bundle.getString(StudentHistoryLaboratoryListActivity.LAB_RESERVE_ID_KEY);
            labName = bundle.getString(StudentHistoryLaboratoryListActivity.LAB_RESERVE_NAME_KEY);
        }


        topTitleTv.setText("实验室");
//        topTitleTv.setText(labName);
        topBackLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StudentHistoryLaboratoryListActivity.this.finish();
            }
        });

        laboratoryScanQrcodeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //启动扫描二维码
                int ing = 0;
                for (int i = 0; i < operationList.size(); i++) {
                    if (URLDecoderUtil.getDecoder(operationList.get(i).getOperatioinState()).equals("0")){
                        ing++;
                    }
                }
                if (ing == 0){
                    startQRcode();

                }else {
                    ToastUtil.showToast("您有正在使用的设备，无法使用新的设备");
                }

            }
        });

        noDataEmptyView.setNoLab(R.string.no_history_lab, R.string.no_null);
        noDataEmptyView.setOnReLoadClickListener(new NoDataEmptyView.OnReLoadClickListener() {
            @Override
            public void onReloadClick(View v) {
                laboratoryListRecyclerView.refresh();
            }
        });
        laboratoryListRecyclerView.setEmptyView(noDataEmptyView);
        laboratoryListRecyclerView.setRefreshMode(1);
        laboratoryListRecyclerView.setLayoutManager(new LinearLayoutManager(this));


        laboratoryListRecyclerView.addOnRefreshListener(new RefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDeviceOperationListHttpRequest();
            }

            @Override
            public void onLoadMore() {

            }
        });

        laboratoryListRecyclerView.refresh();

    }

    private void removeDeviceOperation(final int pos) {
        ProgressDialogUtils.showProgressDialog(this, null, R.string.delete_lab);
        HttpUtil.removeDeviceOperation(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                SharedXmlUtil.getInstance().getHospitalId(), operationList.get(pos).getLabReserveMemberOperationID(), new DisposableObserver<StudentApplyReserveReturn>() {
                    @Override
                    public void onNext(StudentApplyReserveReturn studentApplyReserveReturn) {
                        if (studentApplyReserveReturn.getResult().equals(ErrorCodeReturn.success + "")) {
                            operationList.remove(pos);
                            mListAdapter.setList(operationList);
                            mListAdapter.notifyItemRemoved(pos);
                            ToastUtil.showToast("删除成功");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ProgressDialogUtils.dismissProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        ProgressDialogUtils.dismissProgressDialog();
                    }
                });
    }

    private void startQRcode() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setPrompt("请扫描实验设备二维码");
        integrator.setCaptureActivity(ScanPortraitActivity.class);
        integrator.initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null || !result.getContents().contains("DEVICE")) {
                ToastUtil.showToast("扫描设备有问题，请扫描正确的设备二维码");
            } else {
                String encryptDeviceID = result.getContents().split("\\^")[2];
                HttpUtil.scanQRcodeGetDeviceInfo(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                        SharedXmlUtil.getInstance().getHospitalId(), SharedXmlUtil.getInstance().getUserIdentityId(), labReserveID, encryptDeviceID, new DisposableObserver<ScanDeviceQRCodeResult>() {
                            @Override
                            public void onNext(ScanDeviceQRCodeResult scanDeviceQRCodeResult) {
                                if (scanDeviceQRCodeResult.getResult().equals(ErrorCodeReturn.success + "")) {
                                    SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(scanDeviceQRCodeResult.getData().getToken()));

                                    //获取模型训练详情接口
                                    SearchDeviceDetailHttpRequest(URLDecoderUtil.getDecoder(scanDeviceQRCodeResult.getData().getLabReserveMemberOperation().getLabReserveMemberOperationID()), -1);

                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * //获取模型训练详情接口
     *
     * @param labReserveMemberOperationID
     */
    private void SearchDeviceDetailHttpRequest(String labReserveMemberOperationID, final int pos) {
        HttpUtil.searchDeviceDetail(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                SharedXmlUtil.getInstance().getHospitalId(), labReserveMemberOperationID, new DisposableObserver<SearchDeviceDetailResult>() {
                    @Override
                    public void onNext(SearchDeviceDetailResult searchDeviceDetailResult) {
                        if (searchDeviceDetailResult.getResult().equals(ErrorCodeReturn.success + "")) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchDeviceDetailResult.getData().getToken()));

                            Bundle bundle = new Bundle();
                            bundle.putSerializable(SubmitLabActivity.LAB_RESERVE_MEMBER_OPERATION_KEY, searchDeviceDetailResult.getData().getLabReserveMemberOperationInfo());

                            //已经完成
                            if (pos != -1 && URLDecoderUtil.getDecoder(operationList.get(pos).getOperatioinState()).equals("1")) {
                                openActivity(ShowLabOperationActivity.class, bundle);
                            } else {
                                //正在进行
                                openActivity(SubmitLabActivity.class, bundle);
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    protected void onResume() {
        super.onResume();
//        laboratoryListRecyclerView.refresh();
    }

    /**
     * 获取实验模型训练列表
     */
    private void getDeviceOperationListHttpRequest() {
        operationList.clear();
        HttpUtil.getDeviceOperationList(SharedXmlUtil.getInstance().getDeviceId(), SharedXmlUtil.getInstance().getToken(),
                SharedXmlUtil.getInstance().getHospitalId(), labReserveMemberID, new DisposableObserver<DeviceOperationListResult>() {
                    @Override
                    public void onNext(DeviceOperationListResult deviceOperationListResult) {
                        if (deviceOperationListResult.getResult().equals(ErrorCodeReturn.success + "")) {

                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(deviceOperationListResult.getData().getToken()));

                            for (DeviceOperationListResult.DataBean.LabReserveMemberOperationListBean d:deviceOperationListResult.getData().getLabReserveMemberOperationList()) {
                             if (d.getOperatioinState().equals("1")) {
                                 operationList.add(d);
                             }
                            }

                            initRecyclerList();
                        } else {

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                       laboratoryListRecyclerView.refreshComplete();
                    }

                    @Override
                    public void onComplete() {
                        laboratoryListRecyclerView.refreshComplete();
                    }
                });
    }

    private void initRecyclerList() {
        mProgressBar.setVisibility(View.GONE);
        mListAdapter = new LaboratoryListAdapter(this);
        mListAdapter.setList(operationList);
        laboratoryListRecyclerView.setAdapter(mListAdapter);

        mListAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                SearchDeviceDetailHttpRequest(URLDecoderUtil.getDecoder(operationList.get(pos).getLabReserveMemberOperationID()), pos);
            }
        });

        /*mListAdapter.setOnItemLongClickListener(new RecyclerBaseAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(final int pos) {
                ProgressDialogUtils.showAskDialog(StudentHistoryLaboratoryListActivity.this, "注意", "是否要删除这个模型记录", "确定", "取消", new ProgressDialogUtils.OnClickDialogBtnListenner() {
                    @Override
                    public void onClickDialogBtn(int btnId) {

                        if (btnId == 1) {
//                            Log.e(TAG, "onClickDialogBtn: "+pos);
                            removeDeviceOperation(pos);
                        }
                    }
                }, true);
            }
        });*/
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_laboratory_list;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        noDataEmptyView.setNoLab(R.string.no_history_lab, R.string.no_null);
        laboratoryListRecyclerView.setEmptyView(noDataEmptyView);
        laboratoryListRecyclerView.refresh();
    }

    @Override
    protected void onNetworkDisConnected() {
        operationList = null;

        noDataEmptyView.setNoNetWork();
        laboratoryListRecyclerView.setEmptyView(noDataEmptyView);
        mListAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
